package util.validate
{
	import mx.controls.DateField;
	import mx.events.ValidationResultEvent;
	import mx.validators.ValidationResult;
	import mx.validators.Validator;
	
	public class IdentificationValidator extends Validator
	{
		public function IdentificationValidator()
		{
			super();
		}
		
		
		// 身份证校验证
		private const identitycard_regex:RegExp = /^\d{17}\[\dxX\]\|\d{14}\[\dxX\]$/;
		public  const identitycard_errorString:String="请输入15位或18位的身份证号";
		
		
		
		
		private var _invalidDateError:String="身份证号码包含非法日期";
		private var _invalidCharError:String ="身份证号码包含非法字符";
		private var _digitError:String = "身份证号应为15或者18位";
		
		public function get digitError():String
		{
			return _digitError;
		}

		public function set digitError(value:String):void
		{
			_digitError = value;
		}

		public function get invalidCharError():String
		{
			return _invalidCharError;
		}

		public function set invalidCharError(value:String):void
		{
			_invalidCharError = value;
		}

		public function get invalidDateError():String
		{
			return _invalidDateError;
		}

		public function set invalidDateError(value:String):void
		{
			_invalidDateError = value;
		}

		override protected function doValidation(value:Object):Array {
			// Convert value to a Number.
			var inputValue:String = String(value);
			
			var results:Array;
			
			// Clear results Array.
			results = [];
			
			// Call base class doValidation().
			results = super.doValidation(value);        
			// Return if there are errors.
			
			//if (!identitycard_regex.test(inputValue)) {
			//	results.push(new ValidationResult(true, null, "NaN", 
			//		identitycard_errorString));
			//	return results;
			//} 
			for(var i:int = 0; i < inputValue.length; i++)
			{
				var c:String = inputValue.charAt(i);
				if (isNaN(parseInt(c)))
				{
					if(!(i==17 && (c="X"||"x"))) {
						results.push(new ValidationResult(
							true, null, "invalidChar", invalidCharError));
						return results;
					}
					
				}
				
			}		
			var dateStr:String;
			if (inputValue.length	== 18)
			{
				dateStr	= inputValue.substr(6, 8);
				if(!DateField.stringToDate(dateStr, "YYYYMMDD"))
				{
					results.push(new ValidationResult(
						true, null, "invalidDate",
						invalidDateError));
					return results;
				}
			}else if(inputValue.length == 15)	{
				dateStr	= inputValue.substr(6,	6);
				if(!DateField.stringToDate(dateStr, "YYMMDD"))
				{
					results.push(new ValidationResult(
						true, null, "invalidDate",
						invalidDateError));
					return results;
				}
			}else{
				results.push(new ValidationResult(
					true, null, "digit", 
					digitError));
				return	results;
			}
			
			return results;
		}
	}
}